package com.itealabs.postjson.ext;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import com.itealabs.postjson.JsonCallWaiter;
import com.itealabs.postjson.JsonCallWaiterLocator;

/**
 * Load JsonCallWaiter from Spring IOC Container.
 * @version $Id: JsonCallWaiterSpringLocator.java 27 2010-08-14 16:03:06Z iteahere $
 * @author itea
 * 2010-4-17
 */
public class JsonCallWaiterSpringLocator implements JsonCallWaiterLocator, BeanFactoryAware {

	private boolean supportPojo = false;
	
	private BeanFactory beanFactory;
	
	public JsonCallWaiter getCallWaiter(String method) {
		String m = method;
		String cutm = method;
		while(true) {
			try {
				Object obj = beanFactory.getBean(m);
				if (obj instanceof JsonCallWaiter)
					return (JsonCallWaiter) obj;
				else if (supportPojo)
					return new ReflectionJsonCallWaiter(obj);
			} catch(NoSuchBeanDefinitionException e) {
				cutm = m.replaceAll("\\.[\\w\\d_]+$", "");
				if(m.equals(cutm)) break;
				m = cutm;
			}
		}	
		return null;
	}

	public void setBeanFactory(BeanFactory arg0) throws BeansException {
		this.beanFactory = arg0;
	}

	public boolean isSupportPojo() {
		return supportPojo;
	}

	public void setSupportPojo(boolean supportPojo) {
		this.supportPojo = supportPojo;
	}

}
